package com.whub507.msgmanager.sso.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Locale;
import java.util.regex.Pattern;

public final class DrapUtils {

	private static final Locale DEFAULT_LOCALE = Locale.getDefault();

	private static String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
	private static Pattern p = Pattern.compile(regEx);

	public static Locale getDefaultLocale() {
		return DEFAULT_LOCALE;
	}

	public static void closeQuietly(Closeable c) {
		if (null != c) {
			try {
				c.close();
			} catch (IOException e) {
			}
		}
	}

	public static void handleThrowable(Throwable t) {
		t.printStackTrace();
	}

	public static String getThrowableStackTrace(Throwable t) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			PrintStream pw = new PrintStream(bos);
			t.printStackTrace(pw);
			return bos.toString("UTF-8");
		} catch (Exception e) {
			t.printStackTrace();
			return t.getMessage();
		}
	}

	/**
	 * 获取本机的IP地址
	 * 
	 * @return
	 * @throws Exception
	 */
	public static InetAddress getLocalHostLANAddress() {
		try {
			InetAddress candidateAddress = null;
			// 遍历所有的网络接口
			for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
					.hasMoreElements();) {
				NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
				// 在所有的接口下再遍历IP
				for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
					InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
					if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
						if (inetAddr.isSiteLocalAddress()) {
							// 如果是site-local地址，就是它了
							return inetAddr;
						} else if (candidateAddress == null) {
							// site-local类型的地址未被发现，先记录候选地址
							candidateAddress = inetAddr;
						}
					}
				}
			}
			if (candidateAddress != null) {
				return candidateAddress;
			}
			// 如果没有发现 non-loopback地址.只能用最次选的方案
			InetAddress jdkSuppliedAddress = InetAddress.getLoopbackAddress();
			return jdkSuppliedAddress;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T readValue(ObjectMapper omapper, byte[] src, Class<T> valueType)
			throws IOException, JsonParseException, JsonMappingException {
		return (T) omapper.readValue(src, valueType);
	}

	public static <T> T readValue(ObjectMapper omapper, String content, Class<T> valueType)
			throws IOException, JsonParseException, JsonMappingException {
		return omapper.readValue(content, valueType);
	}

	public static String validate(String s) {
		return s;
	}

	public static Object validateObject(Object obj) {
		return obj;
	}

	public static String validateSpecialChar(String s) {
		if (s != null && p.matcher(s).find())
			throw new RuntimeException("The input [" + s + "] contains special character");
		
		return s;
	}

	/**
	 * 处理希望加入json的字符串
	 * @param s
	 * @return
	 */
	public static Object trimForJson(String s) {
		s = s.replaceAll("\\\\", "");
		s = s.replaceAll("\\\"", "");
		
		return s;
	}

}
